<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>serverTwo</title>
  </head>
  <body>
    我是serverTwo
    <button id="btn">给父页面传值</button>
    <div id="text">111111111111</div>
    <script>
      window.onload = function () {
        const btn = document.getElementById("btn");
        const ORIGIN = "http://127.0.0.1:3000";
        let source;
        function receiveMessage(event) {
          // 我们能相信信息的发送者吗?  (也许这个发送者和我们最初打开的不是同一个页面).
          if (event.origin !== ORIGIN) return;
          text.innerText = event.data;
          if (!source) {
            source = event.source;
          }
        }
        window.addEventListener("message", receiveMessage, false);

        btn.onclick = function () {
          // 由父页面先通讯后再给父页面传值是比较安全的方式
          if (source) {
            source.postMessage("我是serverTwo", ORIGIN);
          } else {
            alert("由父页面先通讯后再给父页面传值是比较安全的方式");
          }
        };
      };
    </script>
  </body>
</html>
